package com.bestflashsolutions.red5Streaming
{
	import com.bestflashsolutions.CommonUtils;
	import com.bestflashsolutions.app.AppUserDataInfo;
	import com.bestflashsolutions.components.DJStringUtil;
	import com.bestflashsolutions.events.ChatUpdateEvent;
	import com.bestflashsolutions.phpRequest.PHPRequest;
	
	import flash.events.Event;
	import flash.events.NetStatusEvent;
	import flash.events.SyncEvent;
	import flash.net.NetConnection;
	import flash.net.ObjectEncoding;
	import flash.net.Responder;
	import flash.net.SharedObject;
	
	import mx.collections.ArrayCollection;
	import mx.controls.Alert;
	import mx.core.UIComponent;
	import mx.formatters.DateFormatter;

	public class AppChatManager extends UIComponent
	{
		private var _serverName:String = "";
		private var _serverApp:String = "";
		
		private var ncChat:NetConnection;
		private var chatMessageRoomTSO:SharedObject;
		
		private var xmlDataHistory:XML = XML("<messages></messages>");
		private var roomNme:String = "";
		private var roomType:int = 0;
		
		public function set xmlHistory(val:String):void{
			if(val != "")
				xmlDataHistory = XML(val);
		}
		
		public function AppChatManager(server: String, app:String, roomName:String = "public", roomtype:int = 0)
		{
			//Alert.show(roomName);
			_serverName = server;
			_serverApp = app;
			roomType = roomtype;
			//trace(roomName);
			ncChat = new NetConnection();
			AppUserDataInfo.getInstance().arrChatNetConnList.push(ncChat);
			ncChat.objectEncoding = ObjectEncoding.AMF0;
			ncChat.addEventListener(NetStatusEvent.NET_STATUS, onNetRoomStatus);	
			var chatMessageInfo:Object = {userName:"none"};		
			ncChat.connect("rtmp://"+server+"/"+app+"/" + roomName, chatMessageInfo);
			roomNme = roomName;
			
			var req: PHPRequest = new PHPRequest(AppUserDataInfo.getInstance().phpReq, checkRetrieve);
			var params = req.params;
			
			params["command"] = "retrievemessagehistory";
			params["roothpath"] = AppUserDataInfo.getInstance().httpRootPath;
			params["filesavename"] = roomNme+".xml";
			params["roomguid"] = AppUserDataInfo.getInstance().userRoomGuid;
			//Send to PHP
			req.request();
		}
		
		private function checkRetrieve(event: Event) {
			trace(event.target.data);
			var xmlres:XML = XML(event.target.data);
			xmlHistory = xmlres.messages;//event.target.data;
		}
		
		public function sendMessages(obj:Object):void{
			
			ncChat.call("sendMessageToRoom", new Responder(onResult, onStatus), obj);
			var isDatePresent:Boolean = false;	
			var xmlMessage:String = "<data message='"+DJStringUtil.escapeHTML(obj.message)+"' user='"+obj.userName+"' datetime='"+currentDateTimeString()+"'/>";
			for each (var prop:XML in xmlDataHistory.item){
				if(prop.@date == currentDateString()){
					prop.appendChild(XMLList(xmlMessage));
					isDatePresent = true;
					break;
				}
			}
			
			if(!isDatePresent){
				var xmlListData:XMLList = XMLList("<item date='"+currentDateString()+"'></item>");
				xmlListData.appendChild(XMLList(xmlMessage));
				xmlDataHistory.appendChild(xmlListData);
			}
			
			trace(xmlDataHistory.toString());	
			//CommonUtils.log((new Date()).toTimeString() + "-" + (new Date()).getMilliseconds() + " = " +" SendMessage::sendMessages()");
			var req: PHPRequest = new PHPRequest(AppUserDataInfo.getInstance().phpReq, checkSave);
			var params = req.params;
			
			params["command"] = "addmessagehistory";
			params["roothpath"] = AppUserDataInfo.getInstance().httpRootPath;
			params["filesavename"] = roomNme;
			params["filesave"] = xmlDataHistory.toString();
			params["roomguid"] = AppUserDataInfo.getInstance().userRoomGuid;
			params["roomtype"] = roomType;
			//Send to PHP
			req.request();
		}
		
		private function checkSave(event: Event) {
			trace(event.target.data);
		}
		
		private function currentDateTimeString():String
		{               
			var CurrentDateTime:Date = new Date();
			var CurrentDF:DateFormatter = new DateFormatter();
			CurrentDF.formatString = "MM/DD/YY LL:NN:SS A"
			var DateTimeString:String = CurrentDF.format(CurrentDateTime);
			return DateTimeString;
		}
		
		private function currentDateString():String
		{               
			var CurrentDateTime:Date = new Date();
			var CurrentDF:DateFormatter = new DateFormatter();
			CurrentDF.formatString = "MM/DD/YY"
			var DateTimeString:String = CurrentDF.format(CurrentDateTime);
			return DateTimeString;
		}
		
		private function onStatus(event:NetStatusEvent):void
		{		
			//Alert.show(String(event.info));
		}
		
		private function onResult(obj:Object):void 
		{
			//Alert.show(String(obj));
		}
		
		private function onNetRoomStatus(event:NetStatusEvent):void
		{
			switch(event.info.code) 
			{
				case "NetConnection.Connect.Success" :
					ncChat.client = this;
					chatMessageRoomTSO = SharedObject.getRemote("RoomTSO", ncChat.uri, false);
					chatMessageRoomTSO.addEventListener(SyncEvent.SYNC, doOnRoomTSOSync);
					chatMessageRoomTSO.connect(ncChat);
					break;
				case "NetConnection.Connect.Failed" :
					ncChat = null;
					Alert.show("Could not connect to room.");
					break;
				case "NetConnection.Connect.Closed" :
					//Alert.show("Connection Close");
					break;
				case "NetConnection.Connect.InvalidApp" :
					ncChat = null;
					Alert.show("An error occured.");
					break;
				case "NetConnection.Connect.AppShutDown" :	
					//Alert.show("Connection AppShutDown");
					break;
				case "NetConnection.Connect.Rejected" :
					//Alert.show("Connection Rejected");
					break;
				default:
					break;
			}
		}
		
		private function doOnRoomTSOSync(event:SyncEvent):void
		{
			var data:Object;
			var item:Object;
			data = chatMessageRoomTSO.data;
			for(item in data)
			{
				if(item == "ChatMessageInfoMap")
				{
					var chatMessageInfoMapDataItem:Object = data[item];
					var chatMessageInfoArrayTemp:Array = new Array();
					for(var chatMessageInfoMapItem:String in chatMessageInfoMapDataItem)
					{						
						chatMessageInfoArrayTemp.push({userName : chatMessageInfoMapDataItem[chatMessageInfoMapItem]["userName"],
							separator: ":",
							userMessage : chatMessageInfoMapDataItem[chatMessageInfoMapItem]["message"]});
						
						var strMessage:String = chatMessageInfoMapDataItem[chatMessageInfoMapItem]["message"];
						var strUserName:String = chatMessageInfoMapDataItem[chatMessageInfoMapItem]["userName"];
							
						var xmlMessage:String = "<data message='"+DJStringUtil.escapeHTML(strMessage)+"' user='"+strUserName+"' datetime='"+currentDateTimeString()+"'/>";
						var i:int = 0;
						
						for each (var prop:XML in xmlDataHistory.item){
							if(prop.@date == currentDateString()){
								var hasmessage:Boolean = false;
								for each(var props:XML in prop.data){
									trace(props.@message," == ",DJStringUtil.escapeHTML(strMessage));
									trace(props.@user," == ",strUserName);
									if(props.@message == DJStringUtil.escapeHTML(strMessage) && props.@user == strUserName){
										hasmessage = true;
										break;
									}
								}
								
								if(!hasmessage)
									prop.appendChild(XMLList(xmlMessage));
								
								break;
							}							
							i++;
						}
						trace(xmlDataHistory.toString());
					}
					dispatchEvent(new ChatUpdateEvent(ChatUpdateEvent.DATA_CHANGE, false, false, chatMessageInfoArrayTemp));
					//chatMessageInfoArrayCollection = new ArrayCollection(chatMessageInfoArrayTemp.reverse());
				}
			}
			
			/*var req: PHPRequest = new PHPRequest(AppUserDataInfo.getInstance().phpReq, checkRetrieve);
			var params = req.params;
			
			params["command"] = "retrievemessagehistory";
			params["roothpath"] = AppUserDataInfo.getInstance().httpRootPath;
			params["filesavename"] = roomNme+".xml";
			params["roomguid"] = AppUserDataInfo.getInstance().userRoomGuid;
			//Send to PHP
			req.request();*/
		}
	}
}